package com.tange.ai.iot.client.gnssa.play

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.graphics.*
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import com.bumptech.glide.Glide
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityDeviceLiveBinding
import com.tange.ai.iot.client.gnssa.utils.Utils
import com.tange.ai.iot.core.media.capture.video.CameraId
import com.tange.ai.iot.core.media.capture.video.CaptureObserver
import com.tange.ai.iot.core.media.capture.video.CodecType
import com.tange.ai.iot.core.media.capture.video.VideoCapture
import com.tange.ai.iot.core.media.capture.video.VideoCaptureConfigure
import com.tange.ai.iot.core.media.capture.video.VideoFrame
import com.tange.ai.iot.core.media.capture.video.processor.RotationProcessor
import com.tange.base.toolkit.*
import com.tange.core.device.facade.ConnectStatus
import com.tange.core.device.facade.DeviceFacade
import com.tange.core.device.facade.Status
import com.tange.core.device.manage.DeviceInfoQuery
import com.tange.core.media.captor.MediaCaptor
import com.tange.core.media.render.AudioMode
import com.tange.core.media.render.DeviceMediaRender
import com.tange.core.media.render.DeviceScreenRecord
import com.tange.core.media.source.impl.live.DeviceLiveMediaSource
import com.tange.core.trouble.shooting.entry.DebuggingAssistant
import com.tange.core.universal.instructions.BasicInstruction
import com.tange.core.universal.instructions.FeederInstruction
//import com.tange.module.media.play.util.BitmapUtil
import com.tg.appcommon.android.Packet
import com.tg.appcommon.android.TGLog
import com.tg.data.media.AudioRecorder
import java.io.File
import java.text.DecimalFormat
import java.util.*


class DeviceLiveActivityV0 : AppCompatActivity() {

    companion object {
        private const val TAG = "DeviceLiveActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"
        private const val PARAM_VIDEO_COVER = "PARAM_VIDEO_COVER"
        private const val PARAM_LAN_MODE = "PARAM_LAN_MODE"
        private const val INSTRUCTION_DEV_INFO_REQ = 0x0330
        private const val ROTATE_90_ON_CAPTURE = false // 演示视频采集的旋转能力

        fun launch(context: Context, deviceId: String, videoCoverUrl: String = "") {
            context.startActivity(Intent(context, DeviceLiveActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
                putExtra(PARAM_VIDEO_COVER, videoCoverUrl)
            })
        }

        fun launchLanMode(context: Context, deviceId: String) {
            context.startActivity(Intent(context, DeviceLiveActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
                putExtra(PARAM_LAN_MODE, true)
            })
        }
    }

    private var albumPath = Environment.getExternalStorageDirectory()
        .toString() + File.separator + Environment.DIRECTORY_DCIM

    private lateinit var deviceId: String

    private lateinit var binding: ActivityDeviceLiveBinding

    private lateinit var deviceFacade: DeviceFacade
    private lateinit var deviceLiveMediaSource: DeviceLiveMediaSource
    private lateinit var deviceMediaRender: DeviceMediaRender

    private var lastDelayUpdate = 0L
    private var isLandscape = false
    private var rendered = false
    private var hasSdCard = false

    /** 本地直连模式 */
    private var lanMode = false

    private var timeZone: TimeZone = TimeZone.getDefault()

    private var mediaCaptor: MediaCaptor? = null

    private var deviceSupportAec = false

    private lateinit var connectStatusObserver : Consumer<ConnectStatus>

    private var videoCaptureConfigure: VideoCaptureConfigure? = null
    private  var fileName = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        binding = ActivityDeviceLiveBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            Utils.setDarkStatusBar(this@DeviceLiveActivityV0, Color.TRANSPARENT)
        }

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)!!
        lanMode = intent.getBooleanExtra(PARAM_LAN_MODE, false)

        val coverUrl = if (intent.hasExtra(PARAM_VIDEO_COVER)) intent.getStringExtra(PARAM_VIDEO_COVER) else ""
        if (!TextUtils.isEmpty(coverUrl)) {
            binding.cover.visible()
            Glide.with(this@DeviceLiveActivityV0).load(coverUrl).into(binding.cover)
        }

        // 初始化调试助手，设置 顶部的 标题 为触发入口
//        DebuggingAssistant.attach(this, binding.name).apply {
//            deviceId = this@DeviceLiveActivity.deviceId
//        }

        connectStatusObserver = Consumer<ConnectStatus> {
            TGLog.i(TAG, "[connect-status] ${it.status}")
            ui {
                if (it.status != Status.SUCCESS) {
                    if (it.status == Status.DISCONNECTED_BY_DEVICE) {
                        Tips.show("设备侧主动断开了连接，将在3秒后自动关闭页面")
                        binding.loading.postDelayed({
                            finish()
                        }, 3000L)
                    } else if (it.status == Status.FAILED) {
                        binding.loading.gone()
                        binding.connect.visible()
                        binding.connect.text = "重试"
                        Tips.show("连接失败：$it")
                    } else {
                        binding.loading.visible()
                    }
                } else {
                    if (rendered) {
                        binding.loading.gone()
                    }

                    quueryDeviceAbilities()

                    queryStorageConfigure()
//                    queryFeeder()
                }
            }
        }

        // 创建设备交互模块
        deviceFacade = DeviceFacade(deviceId).apply {

            enableLanMode(lanMode)

            // 监听连接状态变化
            observeConnectStatus(connectStatusObserver)
        }

        // 创建实时媒体数据源
        deviceLiveMediaSource = DeviceLiveMediaSource(deviceFacade).apply {
            onFrameRate = Consumer {
                val df = DecimalFormat("#.00")
                binding.frameRateLabel.text = "${df.format(it)} FPS"
            }

            onBitrate = Consumer {
                val df = DecimalFormat("#.00")
                binding.bitrateLabel.text = "${df.format(it)} kB/s"
            }
        }

        // 创建媒体播放器
        deviceMediaRender = DeviceMediaRender(this, deviceLiveMediaSource).apply {

            if (AudioRecorder.FORCE_MODE_IN_COMMUNICATION) {
                TGLog.i(TAG, "[onCreate] FORCE_MODE_IN_COMMUNICATION")
                audioOutputChannel = AudioMode.MODE_IN_COMMUNICATION
            }

            mute(false)

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                TGLog.i(TAG, "[first-rendered] ")
                rendered = true
                binding.loading.gone()
            }

            renderStatusObserver = object : DeviceMediaRender.RenderStatusObserver {
                override fun onStart() {
                    binding.videoChatControl.post {
                        binding.videoChatControl.visible()
                    }
                }

                override fun onComplete() {
                    binding.videoChatControl.post {
                        binding.videoChatControl.gone()
                    }
                }

            }
        }

        deviceMediaRender.onTimestampUpdate = Consumer {
            binding.playTimestamp.post {
                if (binding.playTimestampLayout.visibility != View.VISIBLE) {
                    binding.playTimestampLayout.visible()
                }
                binding.playTimestamp.text = "Device UTC Time: ${DateUtil.getStrToTime(it)}"
            }
        }

        deviceMediaRender.onVideoDelayUpdate = Consumer {
            if (System.currentTimeMillis() - lastDelayUpdate > 1000) {
                lastDelayUpdate = System.currentTimeMillis()
                binding.videoDelayLabel.post {
                    binding.videoDelayLabel.text = "${it}s Delay"
                }
            }
        }

        // 监听录屏的状态
        deviceMediaRender.screenRecord().recordStatusObserver =
            object : DeviceScreenRecord.RecordStatusObserver {
                override fun onStart() {
                    Log.i(TAG, "[RecordStatusObserver][onStart] ")
                }

                override fun onDurationUpdate(duration: Long) {
                    Log.i(TAG, "[RecordStatusObserver][onDurationUpdate] $duration")
                }

                override fun onComplete(success: Boolean, path: String) {
                    Log.i(TAG, "[RecordStatusObserver][onComplete] $success")
                }



            }


        binding.loading.visible()
        binding.audio.setImageDrawable(ContextCompat.getDrawable(this,
            R.drawable.ic_baseline_volume_on_24
        ))
        binding.audio.onClicked { switchAudio() }
        binding.screenShot.onClicked { screenshot() }
        binding.screenRecord.onClicked { screenRecord() }
        binding.talkBack.onClicked { talkback() }
        binding.fullScreen.onClicked { switchFullScreen() }
        binding.back.onClicked { finish() }
        binding.connect.onClicked {
            binding.connect.gone()
            deviceFacade.connect()
        }
        binding.localPlayback.onClicked { launchLocalPlayback() }
        binding.cloudPlayback.onClicked { launchCloudPlayback() }

        binding.resolutions.visible()
        binding.resolutions.onClicked { queryResolutions() }

        if (!lanMode) {
            DeviceInfoQuery.requireTimezone(deviceId) { resp ->

                // 请求设备时区，用于日期展示等用途（若设备不存在出海、手机与设备分处不同时区的场景，可忽略此步骤）
                resp.data?.format()?.let {
                    timeZone = it
                }
            }
        }

    }
    private fun queryFeeder() {
        var feeder =FeederInstruction(deviceFacade)
        feeder.current {
            if (it.success) {
                val maxTimers = it.data?.maxTimers ?: 0
                val maxServings = it.data?.maxServings ?: 0
                TGLog.i(TAG, "[queryFeeder] [current] maxTimers = $maxTimers, maxServings = $maxServings")
            } else {
                TGLog.i(TAG, "[queryFeeder] [current] error = ${it.message}")
            }
        }
        feeder.currentPlans() {
            if (it.success) {
                val plans = it.data
                TGLog.i(TAG, "[queryFeeder] [currentPlans] plans = $plans")
                if (plans != null) {
                    plans.get(0)?.let {
                        TGLog.i(TAG, "[queryFeeder] plan = $it")
                        it.time.hour = 12
                        feeder.updatePlans(plans) {
                            if (it.success) {
                                TGLog.i(TAG, "[queryFeeder] [updatePlans] success")
                            } else {
                                TGLog.i(TAG, "[queryFeeder] [updatePlans] error = ${it.message}")
                            }
                        }
                    }
                }

            } else {
                TGLog.i(TAG, "[queryFeeder] [currentPlans] error = ${it.message}")
            }
        }
        feeder.feed(1){
            if (it.success) {
                TGLog.i(TAG, "[queryFeeder][feed]  success")
            } else {
                TGLog.i(TAG, "[queryFeeder][feed] error = ${it.message}")
            }
        }
    }

    private fun queryStorageConfigure() {
        deviceFacade.instruct
            .create(INSTRUCTION_DEV_INFO_REQ)
            .send {
                if (it.success) {
                    it.data?.let {
                        val totalSize = Packet.byteArrayToInt_Little(it, 40)
                        hasSdCard = totalSize > 0
                        if (hasSdCard) binding.localPlayback.post { binding.localPlayback.visible() }
                    }
                } else {
                    Tips.show("查询设备信息失败")
                }
            }
    }

    private fun quueryDeviceAbilities() {

        BasicInstruction(deviceFacade).queryProperties {
            it.data?.abilities?.let {

                if (it.containsKey("Microphone") && (it["Microphone"] ?: "").isNotEmpty()) {
                    val configure = it["Microphone"] ?: ""
                    deviceSupportAec = configure.lowercase(Locale.getDefault()).contains("aec")
                    TGLog.i(TAG, "[queryScreenConfigure] Microphone.configure = $configure")
                }

                if (it.containsKey("Screen") && (it["Screen"] ?: "").isNotEmpty()) {
                    val configure = it["Screen"] ?: ""

                    TGLog.i(TAG, "[queryScreenConfigure] configure = $configure")

                    val segments = configure.split(":")
                    val encodingFormat = if (segments.size > 0) segments[0] else "h264"
                    val resolution = if (segments.size > 1) segments[1] else "320x240"
                    val widthAndHeight = resolution.split("x")
                    val width = widthAndHeight.getOrNull(0)?.toIntOrNull() ?: 320
                    val height = widthAndHeight.getOrNull(1)?.toIntOrNull() ?: 240
                    val codecType = if (encodingFormat == "h264") CodecType.AVC else CodecType.MJPEG

                    TGLog.i(TAG, "[queryScreenConfigure] width = $width")
                    TGLog.i(TAG, "[queryScreenConfigure] height = $height")
                    TGLog.i(TAG, "[queryScreenConfigure] codecType = $codecType")

                    ui {
                        binding.screenAbility.text = "${codecType}, $resolution"
                    }

                    if (mediaCaptor == null) {
                        TGLog.i(TAG, "[queryScreenConfigure] create mediaCaptor")
                        videoChatPreviewConfigure(codecType, width, height)
                    }
                } else {
                    TGLog.i(TAG, "[queryScreenConfigure] not configured.")
                    videoChatPreviewConfigure(null, 320, 240)
                }
            }
        }
    }

    private fun videoChatPreviewConfigure(codecType: CodecType?, specifyWidth: Int, specifyHeight: Int) {
        videoCaptureConfigure = VideoCaptureConfigure(CameraId.FACING_BACK).apply {
            width = specifyWidth
            height = specifyHeight
        }

        if (codecType != null) {

            binding.videoChatBtn.visible()

            binding.videoChatCamera.onClicked {
                if (mediaCaptor?.videoCapturing == true) {
                    binding.videoChatPreviewContainer.gone()
                    binding.videoChatCover.gone()
                    mediaCaptor!!.stopCaptureVideo()
                    if (videoCaptureConfigure!!.cameraId == CameraId.FACING_FRONT){
                        videoCaptureConfigure = VideoCaptureConfigure(CameraId.FACING_BACK).apply {
                            width = specifyWidth
                            height = specifyHeight
                        }
                    } else {
                        videoCaptureConfigure = VideoCaptureConfigure(CameraId.FACING_FRONT).apply {
                            width = specifyWidth
                            height = specifyHeight
                        }
                    }
                    if (!deviceFacade.connected()) {
                        Tips.show("设备未连接！")
                        return@onClicked
                    }
                    videoCaptureConfigure?.let {
                        binding.videoChatPreviewContainer.visible()
                        binding.videoChatCover.visible()
                        mediaCaptor!!.startCaptureVideo(it)
                    }
                }
            }
            binding.videoChat.onClicked {

                if (!deviceFacade.connected()) {
                    Tips.show("设备未连接！")
                    return@onClicked
                }

                videoCaptureInternal()
            }
        }

        mediaCaptor = MediaCaptor(deviceFacade, applicationContext, codecType ?: CodecType.AVC).apply {

            if (ROTATE_90_ON_CAPTURE) {
                // 若设备由于“屏幕安装角度”等原因，需要我们提前旋转画面，可自行注入图像处理器
                videoCaptor.imageProcessors().add(RotationProcessor(90))
                // 由于上方通过 RotationProcessor 旋转了画面，本地预览需要进行相应逆向旋转
                videoCaptor.rotationOnPreview = VideoCapture.PreviewRotation.CW_270
            }

            videoCaptor.attachPreview(binding.videoChatPreviewContainer, createCenterLayoutParams())

            onTalkbackState = Consumer {
                ui {
                    if (it.success) {
                        // 注意： 若设备不支持AEC，即不支持双向对讲，那么 APP 侧 需要在对讲的时候同时 关闭 来自设备的音频
                        if (!deviceSupportAec) {
                            if (AudioRecorder.FORCE_MODE_IN_COMMUNICATION) { // FORCE_MODE_IN_COMMUNICATION 是调试专用，默认为false，一般情况你无需关心
                                Tips.show("对讲开启成功\n已强制启用客户端AEC")
                            } else {
                                Tips.show("对讲开启成功\n设备不支持AEC，暂关闭音频播放")
                                muteAudio()
                            }
                        } else {
                            if (AudioRecorder.FORCE_MODE_IN_COMMUNICATION) { // FORCE_MODE_IN_COMMUNICATION 是调试专用，默认为false，一般情况你无需关心
                                Tips.show("双向对讲开启成功\n已强制启用客户端AEC")
                            } else {
                                Tips.show("双向对讲开启成功\n已根据能力配置启用客户端AEC")
                            }
                        }
                        if (mediaCaptor?.audioCapturing == true) {
                            binding.talkBack.setImageDrawable(ContextCompat.getDrawable(this@DeviceLiveActivityV0,
                                R.drawable.ic_baseline_mic_on_24
                            ))
                        }
                    } else {
                        Tips.show("对讲开启失败：${it.message}")
                        stopVideoCapture()
                        stopCaptureAudio()
                        binding.talkBack.setImageDrawable(ContextCompat.getDrawable(this@DeviceLiveActivityV0, R.drawable.ic_baseline_mic_off_24))
                    }
                }
            }

            videoCaptor.videoCaptureListener = object : CaptureObserver {
                override fun onError(code: Int, message: String) {
                    ui { Tips.show("视频采集异常：$code, $message") }
                }

                override fun onInitialFramePrepared(size: Pair<Int, Int>) {
                    fileName = DateUtil.getCurrentTime()+".h254"
                    TGLog.d(TAG,"[videoChatPreviewConfigure] VideoFrame onInitialFramePrepared ")
                }

                override fun onPrepared(frame: VideoFrame) {

//                    FileUtil.wirteFile(fileName,frame.buffer)
                    TGLog.d(TAG,"[videoChatPreviewConfigure] VideoFrame codecType:${frame.codecType} keyFrame: ${frame.keyFrame} timestampMs: ${frame.timestampMs} ")
                }
            }

            val audioMode = if (deviceSupportAec) AudioMode.MODE_IN_COMMUNICATION else AudioMode.MODE_NORMAL
            TGLog.i(TAG, "[videoChatPreviewConfigure] audioMode = $audioMode")

            if (deviceSupportAec) {
                deviceMediaRender.audioOutputChannel = AudioMode.MODE_IN_COMMUNICATION
                TGLog.i(TAG, "[videoChatPreviewConfigure] SET RENDER AEC")
            }

            audioCaptor.apply {

                mode = audioMode

                observeStatus {

                }
            }
        }

    }

    private fun videoCaptureInternal() {
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                this.requestPermissions(arrayOf(Manifest.permission.CAMERA), 100)
            }
            Tips.show("赋予摄像头权限后重试")
            return
        }

        if (mediaCaptor?.videoCapturing == true) {
            stopVideoCapture()
            binding.videoChatCameraBtn.gone()
        } else {
            startVideoCapture()
            binding.videoChatCameraBtn.visible()
        }
    }

    private fun startVideoCapture() {
        binding.videoChat.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_video_chat_on))
        binding.videoChatPreviewContainer.visible()
        binding.screenAbility.visible()
        binding.videoChatCover.visible()
        videoCaptureConfigure?.let { mediaCaptor?.startCaptureVideo(it) }
    }

    private fun stopVideoCapture() {
        binding.videoChat.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_video_chat_off))
        binding.videoChatPreviewContainer.gone()
        binding.screenAbility.gone()
        binding.videoChatCover.gone()
        mediaCaptor?.stopCaptureVideo()
    }

    private fun queryResolutions() {
        if (!deviceMediaRender.playing) {
            Tips.show("当前未在播放！")
            return
        }

        if (!deviceFacade.connected()) {
            Tips.show("设备未连接！")
            return
        }

        deviceLiveMediaSource.querySupportedResolutions {
            Log.i(TAG, "[queryResolutions] $it")
            ui {
                if (it.success) {
                    val resolutions = it.data!!
                    val currentResolution = deviceLiveMediaSource.currentVideoResolution()
                    var currentIndex = 0
                    resolutions.forEachIndexed { index, liveResolutions ->
                        if (liveResolutions.value == currentResolution) {
                            currentIndex = index
                        }
                    }
                    val items = Array(resolutions.size) { index -> if (index == currentIndex) "${resolutions[index].label} [当前]" else resolutions[index].label }

                    AlertDialog.Builder(this@DeviceLiveActivityV0)
                        .setTitle("选择视频码流")
                        .setItems(items) { _, which ->
                            run {
                                Tips.show("切换至 ${resolutions[which].label} ...")
                                deviceLiveMediaSource.switchVideoResolution(resolutions[which].value)
                            }
                        }
                        .create()
                        .show()

                } else {
                    Tips.show("查询码流设置失败 ${it.message}")
                }
            }
        }
    }

    private fun launchLocalPlayback() {
        if (!hasSdCard) {
            Tips.show("设备没有插入SD卡")
            return
        }

        DevicePlaybackActivity.launch(this, deviceId)
    }

    private fun launchCloudPlayback() {

        if (lanMode) {
            Tips.show("本地直连模式下不可用")
            return
        }

        CloudPlaybackActivity.launch(this, deviceId)
    }

    override fun onResume() {
        super.onResume()
        TGLog.i(TAG, "[onResume] ")
        deviceLiveMediaSource.enableProduce(true)
        deviceMediaRender.play(true)
    }

    override fun onPause() {
        super.onPause()
        TGLog.i(TAG, "[onPause] ")
        deviceLiveMediaSource.enableProduce(false)
        deviceMediaRender.play(false)

        mediaCaptor?.stopCaptureVideo()
        mediaCaptor?.stopCaptureAudio()
        binding.videoChatPreviewContainer.gone()

        binding.talkBack.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_mic_off_24))
        binding.videoChat.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_video_chat_off))
    }

    override fun onDestroy() {
        super.onDestroy()
        deviceLiveMediaSource.onBitrate = null
        deviceLiveMediaSource.onFrameRate = null
        deviceFacade.disconnect()
        deviceFacade.unObserveConnectStatus(connectStatusObserver)
    }

    private fun createCenterLayoutParams() = FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.MATCH_PARENT,
        FrameLayout.LayoutParams.MATCH_PARENT
    ).apply { gravity = Gravity.CENTER }

    private fun talkback() {

        if (!deviceFacade.connected()) {
            Tips.show("等设备连接成功后，再使用对讲")
            return
        }

        if (!deviceMediaRender.playing) {
            Tips.show("当前未在播放！")
            return
        }

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                this.requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 100)
            }
            Tips.show("需要录音权限")
            return
        }

        if (mediaCaptor?.audioCapturing == true) {
            mediaCaptor?.stopCaptureAudio()
            binding.talkBack.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_mic_off_24))
        } else {
            mediaCaptor?.startCaptureAudio()
            binding.talkBack.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_mic_on_24))
        }
    }

    private fun screenRecord() {

        if (!deviceMediaRender.playing) {
            Tips.show("当前未在播放！")
            return
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                this.requestPermissions(arrayOf(Manifest.permission.READ_MEDIA_IMAGES,Manifest.permission.READ_MEDIA_VIDEO), 100)
                Tips.show("需要存储权限")
                return
            }
        } else {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    this.requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100)
                }
                Tips.show("需要存储权限")
                return
            }
        }

//        deviceMediaRender.setRecordScale(2.0f)
        if (deviceMediaRender.screenRecord().isStarted()) {
            val file = File(albumPath, "TG-${System.currentTimeMillis()}.mp4")
            deviceMediaRender.screenRecord().finish(file.absolutePath) {
                if (it) Tips.show("录屏已保存到 ${file.absolutePath}")
            }
            binding.screenRecord.setImageDrawable(ContextCompat.getDrawable(this,
                R.drawable.ic_video_record_normal
            ))
        } else {
            deviceMediaRender.screenRecord().start()
            binding.screenRecord.setImageDrawable(ContextCompat.getDrawable(this,
                R.drawable.ic_video_record_on
            ))
            Tips.show("开始录屏，再次点击结束录屏")
        }

        Log.i(TAG, "[RecordStatusObserver][onClicked] ")
    }

    private fun switchAudio() {
        if (!deviceMediaRender.muted) {
            muteAudio()
        } else {
            binding.audio.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_baseline_volume_on_24))
            deviceMediaRender.mute(false)
        }
    }

    private fun muteAudio() {
        binding.audio.setImageDrawable(
            ContextCompat.getDrawable(
                this,
                R.drawable.ic_baseline_volume_off_24
            )
        )
        deviceMediaRender.mute(true)
    }

    private fun screenshot() {

        if (!deviceMediaRender.playing) {
            Tips.show("当前未在播放！")
            return
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                this.requestPermissions(arrayOf(Manifest.permission.READ_MEDIA_IMAGES,Manifest.permission.READ_MEDIA_VIDEO), 100)
                Tips.show("需要存储权限")
                return
            }
        } else {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    this.requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100)
                }
                Tips.show("需要存储权限")
                return
            }
        }

        deviceMediaRender.screenshot()?.let {

            val file = File(albumPath, "TG-${System.currentTimeMillis()}.jpg")

            BitmapUtil.saveBitmapToFile(file, it, Bitmap.CompressFormat.JPEG)

            if (file.exists()) {
                val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                val uri = Uri.fromFile(file)
                intent.data = uri
                sendBroadcast(intent)
                Tips.show("截图已保存到 ${file.absolutePath}")
            }
        }
    }

    private fun switchFullScreen() {
        if (isLandscape) {
            binding.bottomLayout.visibility = View.VISIBLE
            binding.topBar.visibility = View.VISIBLE
            binding.opButtons.visibility = View.VISIBLE
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            isLandscape = false
        } else {
            binding.bottomLayout.visibility = View.GONE
            binding.topBar.visibility = View.GONE
            binding.opButtons.visibility = View.GONE
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
            isLandscape = true
            binding.playerContainer.postDelayed({
                Tips.show("使用物理返回键退出全屏")
            }, 1000)
        }

        binding.playerContainer.post {
            deviceMediaRender.resize()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean =
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (isLandscape) {
                switchFullScreen()
                true
            }
            else {
                finish()
                true
            }
        } else super.onKeyDown(keyCode, event)
}